require('dotenv').config();
const Koa = require('koa');
const route = require('koa-route');

const app = new Koa();
const koaBody = require('koa-body')();
const fs = require('fs');
const path = require('path');
const aliyunService = require('./src/aliyunService');
const fileUtil = require('./src/utils/fileUtil');
const { clients } = require('./src/webSocket');

require('./src/utils/cronUtil');

app.use(koaBody);

app.use(
  route.get('/', (ctx) => {
    const html = fs.readFileSync(path.resolve('./web/index.html')).toString();
    ctx.type = 'text/html;charset=utf-8';
    ctx.body = html;
  }),
);
app.use(
  route.post('/deploy/record', (ctx) => {
    const content = fileUtil.readFile();
    ctx.body = {
      content,
    };
  }),
);
app.use(
  route.post('/deploy', (ctx) => {
    const { password, clientId } = ctx.request.body;
    console.log(password, clientId);
    ctx.body = {
      msg: '正在发布',
    };
    // 获取ws客户端
    const client = clients[clientId];
    if (password === process.env.password) {
      ctx.body = { msg: '口令正确' };
      if (client.readyState === client.OPEN) {
        aliyunService.deploy(client);
        // setInterval(() => {
        //   client.send("开始发布," + count++);
        // }, 500);
      }
    } else {
      ctx.body = { msg: '口令错误' };
    }
  }),
);

//  开启定时器

app.listen(1011);
console.log('server port 1011 listening...');
